#include "stdafx.h"
#include "Utilities/utilities.h" // if you use STL, please include this line AFTER all other include
#include "Math.h"
#include "Scene.h"
#include "Camera.h"


//
Scene * Scene::ms_pInstance = NULL;

Scene * Scene::GetInstance() 
{
	if ( ms_pInstance == NULL )
		ms_pInstance = new Scene();
	return ms_pInstance;
}

void Scene::DestroyInstance() 
{
	if ( ms_pInstance )
	{
		ms_pInstance->CleanUp();
		delete ms_pInstance;
		ms_pInstance = NULL;
	}
}

Camera * Scene::GetCamera()
{
	return (m_cameras.at(m_activeCamera));
}

void Scene::Init()
{
	//for (unsigned int i = 0; i < m_objects.size(); i++)
	//{
	//	m_objects.at(i)->Init();
	//}
	m_activeCamera = 0;
}

void Scene::Update(float deltaTime )
{
	for (unsigned int i = 0; i < m_objects.size(); i++)
	{
		m_objects.at(i)->UpdateWorldMat();
	}

	m_cameras.at(m_activeCamera)->Update(deltaTime);
}

void Scene::Draw()
{
	//Draw non-blend objects first
	for (unsigned int i = 0; i < m_objects.size(); i++)
	{	
		if (!m_objects.at(i)->IsBlend())
		{
			m_objects.at(i)->Draw();
		}
	}
	//After that draw blend objects
	for (unsigned int i = 0; i < m_objects.size(); i++)
	{
		if (m_objects.at(i)->IsBlend())
		{
			m_objects.at(i)->Draw();
		}
	}
}

void Scene::CleanUp()
{
	for (unsigned int i = 0; i < m_objects.size(); i++)
	{
		m_objects.at(i)->CleanUp();
		delete (m_objects.at(i));
	}
	for (unsigned int i = 0; i < m_cameras.size(); i++)
	{
		delete (m_cameras.at(i));
	}
}

void Scene::AddObject(Object *obj)
{
	m_objects.push_back(obj);
}

void Scene::RemoveObject(Object *obj)
{
	for (ObjectVector::iterator it = m_objects.begin(); it != m_objects.end(); it++)
	{
		if ( (*it) == obj)
		{
			m_objects.erase(it);
			obj->CleanUp();
			delete obj;
		}
	}
}

void Scene::AddCamera(Camera *cam)
{
	m_cameras.push_back(cam);
}